﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Input;
using System.Xml.Serialization;

namespace UIConfigTool.ViewModel
{
    public class ConfigViewModel
    {
        public ConfigViewModel()
        {
            SaveConfigToFileComand = new RelayCommand<object>(SaveToXmlFile);
        }
        [XmlArray("RootNodes")]
        [XmlArrayItem("RootNode")]
        public List<RootNode> RootNodes { get; set; } = new List<RootNode>() { new RootNode() };
        [XmlIgnore]
        public ICommand SaveConfigToFileComand { get; private set; }
        void SaveToXmlFile(object _)
        {
            // 序列化为 XML
            XmlSerializer serializer = new XmlSerializer(typeof(ConfigViewModel));

            // 将对象序列化为字符串并输出
            using (StringWriter stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, this);
                string xml = stringWriter.ToString();
                Console.WriteLine(xml);
            }

            //或者将对象序列化到文件中
            using (StreamWriter writer = new StreamWriter("device_config.xml"))
            {
                serializer.Serialize(writer, this);
            }
        }
    }
}
